import { useUrlSearchParams, useStorage } from '@vueuse/core'
import { useRoute } from 'vue-router'
import Cookies from 'js-cookie'
import type { Ref } from 'vue'

// Token相关的常量
const TOKEN_KEY = 'access-token'

/**
 * 获取当前平台标识
 * 从URL查询参数中获取p参数
 */
export const getPlaid = (): string | null => {
  const route = useRoute()
  return route?.query?.p as string | null
}

export const getAppid = (): string | null => {
  const route = useRoute()
  return route?.query?.appid as string | null
}

/**
 * 使用js-cookie来管理token
 * 与Vue3的响应式系统集成
 */
export const useAuth = () => {
  // 获取token
  const getToken = (): string | undefined => Cookies.get(TOKEN_KEY)

  // 设置token
  const setToken = (value: string): void => Cookies.set(TOKEN_KEY, value)

  // 清除token
  const clearToken = (): void => Cookies.remove(TOKEN_KEY)

  return {
    getToken,
    setToken,
    clearToken
  }
}

/**
 * 从URL参数获取指定名称的参数值
 */
export const useQueryParams = () => {
  // 获取URL查询参数，自动响应式
  const params = useUrlSearchParams('history')

  // 从URL获取指定参数
  const getQueryParam = (name: string): string | null => {
    const value = params[name]
    return value !== undefined ? String(value) : null
  }

  return {
    params,
    getQueryParam
  }
}

/**
 * 使用持久化存储，替代localStorage的直接使用
 * @param key 存储键名
 * @param defaultValue 默认值
 */
export const useLocalStorage = <T>(key: string, defaultValue: T): Ref<T> => {
  return useStorage(key, defaultValue)
}

/**
 * 使用会话存储，页面关闭即失效
 * @param key 存储键名
 * @param defaultValue 默认值
 */
export const useSessionStorage = <T>(key: string, defaultValue: T): Ref<T> => {
  return useStorage(key, defaultValue, sessionStorage)
}
